<template>
  <div class="dashboard-container">
    <div class="app-container">
      <div v-loading="loading" class="edit-form">
        <el-form label-width="auto">
          <el-row>
            <el-col :span="12">
              <el-form-item label="角色">
                <el-input :value="username" size="mini" class="inputW" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="权限">
                <el-tree
                  ref="permTree"
                  node-key="id"
                  :data="permissionData"
                  show-checkbox
                  default-expand-all
                  :props="{label:'name'}"
                  :default-checked-keys="permIds"
                  check-strictly
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex">
            <el-col>
              <el-form-item>
                <el-button type="primary" size="mini" @click="saveUpload">保存更新</el-button>
                <el-button size="mini" @click="$router.replace('/role')">返回</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { getRoleDetail, uploadPower } from '@/api/role.js'
import { getPermissionList } from '@/api/permission.js'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Assignpermission',
  data() {
    return {
      loading: false,
      username: null,
      permissionData: [],
      permIds: [] // 临时数组(收集第一次初始化页面得到的permIds)
      // permIds是单项绑定 不是双向绑定
    }
  },
  created() {
    this.GetPermissionList() // 获取权限点列表
    this.GetRoleDetail()
  },
  methods: {
    async GetPermissionList() {
      this.loading = true
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      console.log(this.permissionData)
    },
    async GetRoleDetail() { // 角色详情
      const { permIds, name } = await getRoleDetail(this.$route.params.id) // 获取 - 角色详情
      this.username = name // 角色名称
      this.permIds = permIds // 将初始有权限的数组作备份
      this.loading = false
    },
    // 保存更新
    async saveUpload() {
      await uploadPower(this.$route.params.id, this.$refs.permTree.getCheckedKeys())
      this.$router.replace('/role')
      this.$message.success('角色权限分配成功')
    }
  }
}
</script>

<style scoped lang="scss">
.edit-form {
display: flex;
align-items: center;
justify-content: center;
  background: #fff;
  padding: 20px;
  margin-top: 30px;
  .inputW {
    width: 380px
  }
}

.el_checkbox{
  width: 380px;
}
</style>
